package com.easylinkin.security.service;

import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.service.UserService;

import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import site.morn.framework.context.LoginValidator;
import site.morn.util.BeanFunctionUtils;

/**
 * 登录服务
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/8/28
 */
@Service
public class SmLoginService implements UserDetailsService {

  @Resource
  private UserService userService;

  @SuppressWarnings("unchecked")
  @Override
  public UserDetails loadUserByUsername(String s) {
    User user = userService.findByUsername(s);
    if (Objects.isNull(user)) {
      throw new UsernameNotFoundException("User no found:" + s);
    }
    boolean enabled = Optional.ofNullable(user.getDisplay()).orElse(true);
    boolean accountNonLocked = !Optional.ofNullable(user.getLocked()).orElse(false);
    // 登录校验，验证用户可否登录
    if (enabled && accountNonLocked) {
      BeanFunctionUtils.validates(LoginValidator.class, user);
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(),
        user.getPassword(), enabled, true, true, accountNonLocked, Collections.emptyList());
  }
}
